<?php

Yii::import('common.models._base.BaseCoupons');

class Coupons extends BaseCoupons {

    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    public function rules() {
        return array(
            array('name', 'required'),
            array('inprice, inpercentage, apply_discount_to, restrict_by_date, maximum_number_of_redemptions_per_code, maximum_number_of_redemptions_per_user, maximum_number_of_prodcuts_to_discount, require_all_products_to_match, user_restriction, order_limit, minimum_order, maximum_order, status', 'numerical', 'integerOnly' => true),
            array('name', 'length', 'max' => 200),
            array('inprice', 'price_percentage_value'),
            array('valid_from_date', 'from_to_date_value'),
            array('maximum_order', 'maxmin_order_value'),
            array('status,description', 'safe'),
            /* array('maximum_number_of_prodcuts_to_discount', 'maximum_number_of_prodcuts_to_discount_value'), */
            array('valid_from_date, valid_to_date, created', 'safe'),
            array('inprice, inpercentage, apply_discount_to, restrict_by_date, valid_from_date, valid_to_date, maximum_number_of_redemptions_per_code, maximum_number_of_redemptions_per_user, maximum_number_of_prodcuts_to_discount, require_all_products_to_match, , user_restriction, order_limit, minimum_order, maximum_order,status, created,description', 'default', 'setOnEmpty' => true, 'value' => null),
            array('id, name,description, inprice, inpercentage, apply_discount_to, restrict_by_date, valid_from_date, valid_to_date, maximum_number_of_redemptions_per_code, maximum_number_of_redemptions_per_user, maximum_number_of_prodcuts_to_discount, require_all_products_to_match, user_restriction, status, created,minimum_order, order_limit, minimum_order, maximum_order,', 'safe', 'on' => 'search'),
        );
    }

    public function maxmin_order_value($attribute, $params) {
        if ($this->order_limit == 1 && $this->minimum_order == 0 && $this->maximum_order == 0)
            $this->addError($attribute, 'You must specify the minimum or maximum order limit to discount.');
    }

    public function price_percentage_value($attribute, $params) {
        if ($this->inprice == "" && $this->inpercentage == "")
            $this->addError($attribute, 'price or percentage value required.');
    }

    public function from_to_date_value($attribute, $params) {
        if ($this->restrict_by_date == 1 && ($this->valid_from_date == "" || $this->valid_to_date == "")) {
            $this->addError($attribute, 'From date and To date can not be blank.');
        } elseif (($this->valid_from_date != "" && $this->valid_to_date != "") && ($this->valid_from_date > $this->valid_to_date)) {
            $this->addError($attribute, 'To date must be greater than from date.');
        }
    }

    public function maximum_number_of_prodcuts_to_discount_value($attribute, $params) {
        if (($this->apply_discount_to == "3" || $this->apply_discount_to == "4") && $this->maximum_number_of_prodcuts_to_discount == 0)
            $this->addError($attribute, 'You must specify the maximum number of products to discount.');
    }

    public static function deleteClass_course_category_users_restriction_coupon($coupons_id) {
        ClassCourseCategoryUsersRestrictionCoupon::model()->deleteAll('coupons_id=:coupons_id', array(':coupons_id' => $coupons_id));
    }

    public static function getcoupanIdBycoupancode($coupanCode) {
        $couponid = Coupons::model()->findByAttributes(array('name' => $coupanCode));
        return !empty($couponid) ? $couponid->id : '';
    }

    public static function unsetSessionShopingcart() {
        Yii::app()->user->setState('appliedcoupon', NULL);
        Yii::app()->session['shopping_cart_session']='';
         Yii::app()->session['orderid'] = '';
    }

    public static function getOrderofSubtotal($subtotal) {
        $subtotalAfterDiscount = '';
        $couponCode = (Yii::app()->user->hasState('appliedcoupon')) ? Yii::app()->user->getState('appliedcoupon') : '';
        $couponModel = Coupons::model()->findByAttributes(array('name' => $couponCode, 'status' => SkillConfig::STATUS_ACTIVE));
        $price = $couponModel->inprice;
        $percentage = $couponModel->inpercentage;
        $couponRestriction = self::getCouponRescrtion();
        if ($couponRestriction != 'false') {
            if ($price <> "") {
                $subtotalAfterDiscount = $subtotal - $price;
            }
            if ($percentage <> "") {
                $subtotalAfterDiscount = $subtotal - ($subtotal * ($percentage / 100));
            }
        }
        return $subtotalAfterDiscount;
    }

    public static function shopingcartAddProductArray() {
        $shopinCartclassCourseId = array();
        foreach (Yii::app()->shoppingCart->getPositions() as $shopingcart) {
            if (isset($shopingcart->classes_id) && $shopingcart->classes_id <> "") {
                $shopinCartclassCourseId[] = $shopingcart->classes_id;
            }
        }
        return $shopinCartclassCourseId;
    }

    public static function matchproductincouponClassCourseIdarray($couponModel) {
        $couponclassCourseId = array();
        foreach ($couponModel->classCourseCategoryUsersRestrictionCoupons as $couponVal) {
            if (isset($couponVal->classes_id) && $couponVal->classes_id <> "") {
                $couponclassCourseId[] = $couponVal->classes_id;
            }
        }
        return $couponclassCourseId;
    }

    public static function totalofmatchingproducts($couponCode) {
        $shopinCartclassCourseId = array();
        $couponclassCourseId = array();
        $totalofmatchingproductsPrice = 0;
        $totalAmount = 0;
        $couponModel = self::getCouponType($couponCode);
        $price = $couponModel->inprice;
        $percentage = $couponModel->inpercentage;
        $shopinCartclassCourseId = self::shopingcartAddProductArray();
        if (!empty($couponModel)) {
            $couponclassCourseId = self::matchproductincouponClassCourseIdarray($couponModel);
        }
        $dicountPerClasses = array_intersect($shopinCartclassCourseId, $couponclassCourseId);
        foreach (Yii::app()->shoppingCart->getPositions() as $shopingcart) {
            $earlyDscount = ClassBatch::getearlyDscountByBatch($shopingcart->id, $shopingcart->quantity);
            $groupDscountByBatch = ClassBatch::getgroupDscountByBatch($shopingcart->id, $shopingcart->quantity);
            $priceByCalsses = $shopingcart->quantity * $shopingcart->price;
            $priceByCalss = $priceByCalsses - ($earlyDscount + $groupDscountByBatch);
            if (in_array($shopingcart->classes_id, $dicountPerClasses)) {
                $totalofmatchingproductsPrice = $totalofmatchingproductsPrice + $priceByCalss;
            } else {
                $totalAmount = $totalAmount + $priceByCalss;
            }
        }
        if ($price <> "") {
            $subtotalAfterDiscount = $totalofmatchingproductsPrice - $price;
            $subtotalAfterDiscount = $subtotalAfterDiscount + $totalAmount;
        }
        if ($percentage <> "") {
            $subtotalAfterDiscount = $totalofmatchingproductsPrice - ($totalofmatchingproductsPrice * ($percentage / 100));
            $subtotalAfterDiscount = $subtotalAfterDiscount + $totalAmount;
        }
//echo $subtotalAfterDiscount;die;
        return $subtotalAfterDiscount;
    }

    public static function allmatchingproducts($couponCode) {
        $shopinCartclassCourseId = array();
        $couponclassCourseId = array();
        $couponModel = self::getCouponType($couponCode);
        $classArray = array();
        $shopinCartclassCourseId = self::shopingcartAddProductArray();
        if (!empty($couponModel)) {
            $couponclassCourseId = self::matchproductincouponClassCourseIdarray($couponModel);
        }
        $dicountPerClasses = array_intersect($shopinCartclassCourseId, $couponclassCourseId);
        foreach ($dicountPerClasses as $dicountPerClass) {
            $classArray[] = $dicountPerClass;
        }
        return $classArray;
    }

    public static function getCouponRescrtion() {
        $date = date('Y-m-d');
        $total_amt = Yii::app()->session['totalamountcart'];
        $couponclassCourseId = array();
        $shopinCartclassCourseId = array();
        $couponCode = (Yii::app()->user->hasState('appliedcoupon')) ? Yii::app()->user->getState('appliedcoupon') : '';
        $valid_err = 'false';
        $couponModel = Coupons::model()->findByAttributes(array('name' => $couponCode, 'status' => SkillConfig::STATUS_ACTIVE));
        if (!empty($couponModel)) {
            $shopinCartclassCourseId = self::shopingcartAddProductArray();
            $couponclassCourseId = self::matchproductincouponClassCourseIdarray($couponModel);
            $valid_err = 'True';
            $maximumNumberOfuseCode = $couponModel->maximum_number_of_redemptions_per_code;
            $maximumUserUsethiscode = $couponModel->maximum_number_of_redemptions_per_user;
            $restrict_by_date = $couponModel->restrict_by_date;
            $valid_from_date = $couponModel->valid_from_date;
            $valid_to_date = $couponModel->valid_to_date;
            $require_all_products_to_match = $couponModel->require_all_products_to_match;
            $user_restriction = $couponModel->user_restriction;
            $order_limit = $couponModel->order_limit;
            $minimum_order = $couponModel->minimum_order;
            $maximum_order = $couponModel->maximum_order;


            if ($require_all_products_to_match == 1) {
                $dicountPerClasses = array_intersect($shopinCartclassCourseId, $couponclassCourseId);
                if (!count(array_diff($couponclassCourseId, $shopinCartclassCourseId)) && !count(array_diff($shopinCartclassCourseId, $couponclassCourseId))) {
                    $valid_err = 'True';
                } else {
                    $valid_err = 'false';
                }
                if ($valid_err != 'True') {
                    die;
                }
            }
            if ($couponModel->apply_discount_to == 2) {//means total of matching product                
                $dicountPerClasses = array_intersect($shopinCartclassCourseId, $couponclassCourseId);
                $valid_err = (!empty($dicountPerClasses)) ? 'True' : 'false';
                if ($valid_err != 'True') {
                    die;
                }
            }
            if ($couponModel->apply_discount_to == 3) {//means All matching product                
                $dicountPerClasses = array_intersect($shopinCartclassCourseId, $couponclassCourseId);
                $valid_err = (!empty($dicountPerClasses)) ? 'True' : 'false';
                if ($valid_err != 'True') {
                    die;
                }
            }
            if ($maximumNumberOfuseCode != 0) {
                $purchaseOrderCount = count(PurchaseOrder::model()->findAll('coupons_id=' . $couponModel->id));
                $valid_err = ($purchaseOrderCount < $maximumNumberOfuseCode) ? 'True' : 'false';
                if ($valid_err != 'True') {
                    die;
                }
            }
            if ($restrict_by_date == 1) {
                $valid_err = ($valid_from_date <= $date && $valid_to_date >= $date) ? 'True' : 'false';

                if ($valid_err != 'True') {
                    die;
                }
            }
            if ($order_limit == 1) {
                $valid_err = ($minimum_order <= $total_amt && $maximum_order >= $total_amt) ? 'True' : 'false';
            }
        }
        return $valid_err;
    }

    public static function getCouponType($couponCode) {
        $couponid = Coupons::model()->findByAttributes(array('name' => $couponCode));
        return $couponid;
    }

    public static function cheapestmatchingproducts() {
        $chepeastBatchPrice = '';
        foreach (Yii::app()->shoppingCart->getPositions() as $chepeastPrice) {
            $chepeastBatchPrice[] = array('classes_id' => $chepeastPrice->classes_id, 'price' => $chepeastPrice->price);
        }
        usort($chepeastBatchPrice, 'shoppingcart_compare_price');
        return end($chepeastBatchPrice);
    }

    public static function mostexpensivematchingproducts() {
        $expensiveBatchPrice = '';
        foreach (Yii::app()->shoppingCart->getPositions() as $chepeastPrice) {
            $expensiveBatchPrice[] = array('classes_id' => $chepeastPrice->classes_id, 'price' => $chepeastPrice->price);
        }
        usort($expensiveBatchPrice, 'shoppingcart_compare_price');
        return current($expensiveBatchPrice);
    }

    public static function getDiscountPrice($couponCode) {
        $discount = '';
        if ($couponCode->inprice <> "") {
            $discount = $couponCode->inprice;
        }
        if ($couponCode->inpercentage <> "") {
            $discount = $couponCode->inpercentage . '%';
        }

        return $discount;
    }
    
     public static function getTotalDiscountPricecoupon($couponCode,$price) {
        $discount = '';
        if ($couponCode->inprice <> "") {
            $discount = $couponCode->inprice;
        }
        if ($couponCode->inpercentage <> "") {
            $discount = $couponCode->inpercentage;
            $discount=($price * $discount)/100;
          
        }

        return $discount;
    }
   
    

    public static function deleteClassCourseCoupon($couponId) {
        ClassCourseCategoryUsersRestrictionCoupon::model()->deleteAll('coupons_id=:coupons_id', array(':coupons_id' => $couponId));
    }

}